package com.apexedu.sync.node.impl;

import java.util.List;

import com.apexedu.biz.Const;
import com.apexedu.framework.dao.BaseDao;
import com.apexedu.framework.util.DBUtil;
import com.apexedu.identity.entity.TSysMenu;
import com.apexedu.portal.util.DBMUtil;
import com.apexedu.sync.contant.Constants;
import com.apexedu.sync.engine.ISyncContext;
import com.apexedu.sync.entity.SyncAppModelMsg;
import com.apexedu.sync.exception.AuCSyncException;
import com.apexedu.sync.node.ISyncNode;
import com.apexedu.sys.SysConstant;
import com.apexedu.sys.util.BusinessLogUtil;

/**
 * 同步apexssh业务系统菜单资源
 * Created by ly on 2015/1/13.
 */
public class ApexsshMenuNode extends BaseNode implements ISyncNode {
	@Override
	public void execute(ISyncContext context) throws AuCSyncException {
		BaseDao baseDao = context.getBaseDao();
		DBMUtil dbmUtil = context.getDbmUtil(); //多数据源工具类
		try {
			List<TSysMenu> menuList = dbmUtil.queryAllBeanList("select * from t_sys_menu" + " START WITH upmenuid='000' CONNECT BY PRIOR menuid=upmenuid", TSysMenu.class);
			String upmenuid = getParentMenuId(context);
			for (TSysMenu menu : menuList) {
				menu.setBizcode(menu.getMenuid());
				menu.setUpbizcode(menu.getUpmenuid());
				menu.setBelongtoapp(context.getAppid());
				menu.setMenuid(upmenuid + menu.getMenuid().substring(3));
				menu.setUpmenuid(menu.getMenuid().substring(0, menu.getMenuid().length() - 3));
				menu.setSrctype("1"); //菜单

				context.getMapMenu().put(menu.getBizcode(), menu); //保存到集合中，用于校验角色资源关系
			}

			long c = DBUtil.count(" from t_sys_menu t where t.belongtoapp=? and length(menuid)!=6", context.getAppid());
			DBUtil.executeSQL("delete from t_sys_menu t where t.belongtoapp=? and length(menuid)!=6", context.getAppid());
			//TODO 改成basedao

			baseDao.saveAll(menuList);
			String msg = "插入：" + menuList.size() + "条，删除：" + c + "条";
			context.getMsg().getListModelMsg().add(new SyncAppModelMsg(Constants.NodeType.MENU, msg));
			BusinessLogUtil.log(getUserInfo(context), SysConstant.CZDX_T_SYS_MENU, Const.LOG_ACTION_UPDATE, msg);
		} catch (AuCSyncException e) {
			e.printStackTrace();
			log.error("ApexsshMenuNode error : " + e);
			context.getMsg().getListModelMsg().add(new SyncAppModelMsg(Constants.NodeType.MENU, e.getMessage()));
			throw e;
		} catch (Exception e) {
			e.printStackTrace();
			log.error("ApexsshMenuNode error : " + e);
			context.getMsg().getListModelMsg().add(new SyncAppModelMsg(Constants.NodeType.MENU, e.getMessage()));
			throw new AuCSyncException(AuCSyncException.UNKNOWN_SERVICE_ERROR, e.getMessage());
		}
	}
}
